package com.aletto.general_store.ui.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.aletto.general_store.R;
import com.aletto.general_store.configs.SubscribeEventBus;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.entities.WalletAccount;
import com.aletto.general_store.data.model.UserDetails;
import com.aletto.general_store.presenters.core.SimpleTemplate;
import com.aletto.general_store.utils.Enabled;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.ToastUtils;
import com.aletto.general_store.utils.WalletAccountLocalStore;
import com.aletto.general_store.utils.WalletHelper;
import com.aletto.general_store.utils.XHelper;
import com.aletto.general_store.utils.event.FinishEvent;
import com.aletto.general_store.utils.event.LoginEvent;
import com.king.camera.scan.CameraScan;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.Debounce;
import com.sisyphus.spinach.network.views.ToastView;
import com.sisyphus.spinach.utils.watchers.EmptyRule;
import com.sisyphus.spinach.utils.watchers.OnWatcherCallback;
import com.sisyphus.spinach.utils.watchers.TextWatchers;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;

/**
 * 导入钱包，助记词&私钥
 */
public class WalletImportActivity extends AppCompatActivity implements SubscribeEventBus {

    private Button confirmButton;
    private WalletAccount walletAccount;

    private RadioGroup mImportRadioGroup;
    private EditText   mImportContentEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_import);

        XHelper.initTitle(this, R.string.import_wallet);

        mImportRadioGroup = findViewById(R.id.import_group);
        mImportContentEditText = findViewById(R.id.import_content_edit);

        mImportRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            mImportContentEditText.setText("");
            if (checkedId == R.id.mnemonic_radio) {
                mImportContentEditText.setHint(R.string.hint_wallet_import_mnemonic);

            } else if (checkedId == R.id.private_key_radio) {
                mImportContentEditText.setHint(R.string.hint_wallet_import_private_key);
            }
        });

        mImportRadioGroup.check(R.id.mnemonic_radio);

        // 确认导入
        confirmButton = findViewById(R.id.confirm_button);
        TextWatchers.add(new EmptyRule(mImportContentEditText)).setWatcherCallback(confirmButton::setEnabled);
        confirmButton.setOnClickListener(new Enabled(v -> runOnUiThread(this::importWallet)));

        // 二维码
        ImageView rqCodeButton = findViewById(R.id.rq_code_image);
        rqCodeButton.setOnClickListener(v ->
                intentActivityResultLauncher.launch(new Intent(this, QRCodeScanActivity.class)));
    }

    ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                Intent resultData = result.getData();
                if (resultData != null && result.getResultCode() == Activity.RESULT_OK) {
                    String resultExtra = resultData.getStringExtra(CameraScan.SCAN_RESULT);

                    if (resultExtra != null && resultExtra.split(" ").length > 1) { // 助记词
                        mImportRadioGroup.check(R.id.mnemonic_radio);

                    } else { // 私钥
                        mImportRadioGroup.check(R.id.private_key_radio);
                    }

                    mImportContentEditText.setText(resultExtra);
                }
            });

    private void importWallet() {

        int checkedId = mImportRadioGroup.getCheckedRadioButtonId();
        String walletName = new Date().toString(),
                importContent = mImportContentEditText.getText().toString();

        if (checkedId == R.id.mnemonic_radio) {
            walletAccount = WalletHelper.walletFormMnemonic(walletName, importContent);

        } else { // checkedId == R.id.private_key_radio
            walletAccount = WalletHelper.walletFormPrivateKey(walletName, importContent);
        }

        if (walletAccount == null) {
            ToastUtils.makeText(R.string.error_import_wallet_tips);
            return;
        }

        save();
    }


    private void save(){
        new SimpleTemplate<UserDetails>(){

            @Override
            public INetTask.View<UserDetails> view() {
                return new Debounce<>(confirmButton, new ToastView<>(WalletImportActivity.this){
                    @Override
                    public void success(UserDetails data) {
                        super.success(data);
                        Activity context = WalletImportActivity.this;

                        walletAccount.setAvatar(data.getHead_img());
                        walletAccount.setNickname(data.getName());

                        // 存储至本地
                        WalletAccountLocalStore.getInstance().addAccount(walletAccount);

                        // 本地 & 登录
                        LocalConfigStore.getInstance().setWallet(walletAccount);
//                        LocalConfigStore.getInstance().saveToken(data.getUser_token());

                        // 发送通知
                        EventBus.getDefault().post(new LoginEvent());

                        // 跳转编辑
                        startActivity(ProfileActivity.newIntent(context, walletAccount.getAddress()));

                    }
                });
            }

            @Override
            public INetTask.Presenter<UserDetails, INetTask.View<UserDetails>> presenter() {
                return new NetSingleTask<>(DataRepository.getInstance().login(walletAccount.getAddress()));
            }

        }.execute();
    }

    @Subscribe
    public void onEvent(FinishEvent event){
        if (event.target == WalletImportActivity.class) {
            finish();
        }
    }

}
